extends Node

## 物品管理器
## 管理游戏中的所有物品数据和装备系统

enum ItemType {
	EQUIPMENT,
	CONSUMABLE,
	MATERIAL
}

enum EquipmentSlot {
	WEAPON,
	HELMET,
	CHEST,
	LEGS,
	GLOVES,
	BOOTS,
	SHIELD,
	RING1,
	RING2,
	NECKLACE,
	EARRING
}

enum ItemRarity {
	COMMON,
	UNCOMMON,
	RARE,
	EPIC,
	LEGENDARY
}

class ItemData:
	var id: String
	var name: String
	var description: String
	var icon_path: String
	var type: ItemType
	var rarity: ItemRarity
	var stack_size: int = 1
	var value: int = 0
	
	func _init(item_id: String, item_name: String, item_desc: String = "", item_icon: String = ""):
		id = item_id
		name = item_name
		description = item_desc
		icon_path = item_icon

class EquipmentData extends ItemData:
	var slot: EquipmentSlot
	var level_requirement: int = 1
	var enhancement_level: int = 0
	var max_enhancement: int = 15
	
	# 装备属性
	var strength: int = 0
	var agility: int = 0
	var intelligence: int = 0
	var stamina: int = 0
	var spirit: int = 0
	var critical_rate: float = 0.0
	var cooldown_reduction: float = 0.0
	var penetration_rate: float = 0.0
	var critical_damage: float = 0.0
	var physical_defense: int = 0
	var dodge_rate: float = 0.0
	var block_rate: float = 0.0
	var life_steal: float = 0.0
	var toughness: float = 0.0
	var movement_speed: float = 0.0
	var status_resistance: float = 0.0
	var status_hit_rate: float = 0.0
	var elemental_damage: float = 0.0
	
	func duplicate_equipment() -> EquipmentData:
		"""创建装备的副本"""
		var copy = EquipmentData.new(id, name, slot, description, icon_path)
		copy.level_requirement = level_requirement
		copy.enhancement_level = enhancement_level
		copy.max_enhancement = max_enhancement
		copy.rarity = rarity
		copy.stack_size = stack_size
		copy.value = value
		
		# 复制所有属性
		copy.strength = strength
		copy.agility = agility
		copy.intelligence = intelligence
		copy.stamina = stamina
		copy.spirit = spirit
		copy.critical_rate = critical_rate
		copy.cooldown_reduction = cooldown_reduction
		copy.penetration_rate = penetration_rate
		copy.critical_damage = critical_damage
		copy.physical_defense = physical_defense
		copy.dodge_rate = dodge_rate
		copy.block_rate = block_rate
		copy.life_steal = life_steal
		copy.toughness = toughness
		copy.movement_speed = movement_speed
		copy.status_resistance = status_resistance
		copy.status_hit_rate = status_hit_rate
		copy.elemental_damage = elemental_damage
		
		return copy
	
	func _init(item_id: String, item_name: String, equipment_slot: EquipmentSlot, item_desc: String = "", item_icon: String = ""):
		super(item_id, item_name, item_desc, item_icon)
		type = ItemType.EQUIPMENT
		slot = equipment_slot
	
	func get_enhancement_bonus() -> float:
		return 1.0 + (enhancement_level * 0.1)
	
	func get_total_strength() -> int:
		return int(strength * get_enhancement_bonus())
	
	func get_total_agility() -> int:
		return int(agility * get_enhancement_bonus())
	
	func get_total_intelligence() -> int:
		return int(intelligence * get_enhancement_bonus())
	
	func get_total_stamina() -> int:
		return int(stamina * get_enhancement_bonus())
	
	func get_total_spirit() -> int:
		return int(spirit * get_enhancement_bonus())
	
	func get_total_physical_defense() -> int:
		return int(physical_defense * get_enhancement_bonus())
	
	func can_enhance() -> bool:
		return enhancement_level < max_enhancement
	
	func enhance() -> bool:
		if can_enhance():
			enhancement_level += 1
			return true
		return false

class ConsumableData extends ItemData:
	var effect_type: String
	var effect_value: int
	var duration: float = 0.0
	
	func _init(item_id: String, item_name: String, effect: String, effect_val: int, item_desc: String = "", item_icon: String = ""):
		super(item_id, item_name, item_desc, item_icon)
		type = ItemType.CONSUMABLE
		effect_type = effect
		effect_value = effect_val
		stack_size = 99

class MaterialData extends ItemData:
	var material_type: String
	
	func _init(item_id: String, item_name: String, mat_type: String, item_desc: String = "", item_icon: String = ""):
		super(item_id, item_name, item_desc, item_icon)
		type = ItemType.MATERIAL
		material_type = mat_type
		stack_size = 999

class InventorySlot:
	var item_data: ItemData
	var quantity: int = 0
	
	func _init(data: ItemData = null, qty: int = 0):
		item_data = data
		quantity = qty
	
	func is_empty() -> bool:
		return item_data == null or quantity <= 0
	
	func can_add_item(data: ItemData, qty: int) -> bool:
		if is_empty():
			return true
		if item_data.id == data.id and quantity + qty <= data.stack_size:
			return true
		return false
	
	func add_item(data: ItemData, qty: int) -> int:
		if is_empty():
			item_data = data
			quantity = qty
			return 0
		elif item_data.id == data.id:
			var can_add = min(qty, data.stack_size - quantity)
			quantity += can_add
			return qty - can_add
		return qty
	
	func remove_item(qty: int) -> int:
		var removed = min(qty, quantity)
		quantity -= removed
		if quantity <= 0:
			item_data = null
			quantity = 0
		return removed

var item_database: Dictionary = {}
var equipment_slots: Dictionary = {}
var inventory_equipment: Array = []
var inventory_consumable: Array = []
var inventory_material: Array = []

const INVENTORY_SIZE = 200

signal equipment_changed(slot, equipment)
signal inventory_changed()

func _ready():
	_initialize_inventory()
	_load_item_database()

func _initialize_inventory():
	for i in range(INVENTORY_SIZE):
		inventory_equipment.append(InventorySlot.new())
		inventory_consumable.append(InventorySlot.new())
		inventory_material.append(InventorySlot.new())
	
	for slot in EquipmentSlot.values():
		equipment_slots[slot] = null

func _load_item_database():
	# 从JSON文件加载装备数据
	_load_equipments_from_json()
	# 从JSON文件加载消耗品数据
	_load_consumables_from_json()
	# 从JSON文件加载材料数据
	_load_materials_from_json()
	
	print("成功加载 ", item_database.size(), " 个物品数据")

## 为新角色添加初始装备套装
func add_starter_equipment():
	"""为新角色添加一套完整的一级装备"""
	# 一级装备ID列表
	var starter_equipment_ids = [
		"wooden_sword",     # 武器
		"cloth_helmet",     # 头盔
		"cloth_robe",       # 胸甲
		"cloth_pants",      # 腿甲
		"cloth_shoes",      # 靴子
		"wooden_shield",    # 盾牌
		"cloth_gloves",     # 手套
		"copper_ring",      # 戒指
		"leather_necklace", # 项链
		"simple_earring"    # 耳环
	]
	
	# 添加基础消耗品
	var starter_consumables = {
		"health_potion": 5,
		"mana_potion": 3
	}
	
	# 添加装备到背包
	for equipment_id in starter_equipment_ids:
		var equipment = get_item_data(equipment_id)
		if equipment:
			add_item_to_inventory(equipment, 1)
			print("添加初始装备: ", equipment.name)
		else:
			print("警告: 找不到装备 ", equipment_id)
	
	# 添加消耗品到背包
	for consumable_id in starter_consumables:
		var consumable = get_item_data(consumable_id)
		if consumable:
			add_item_to_inventory(consumable, starter_consumables[consumable_id])
			print("添加初始消耗品: ", consumable.name, " x", starter_consumables[consumable_id])
		else:
			print("警告: 找不到消耗品 ", consumable_id)
	
	print("初始装备添加完成")

func _load_equipments_from_json():
	"""从JSON文件加载装备数据"""
	var file = FileAccess.open("res://data/equipments/equipments.json", FileAccess.READ)
	if file == null:
		print("无法打开装备数据文件")
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		print("解析装备JSON数据失败")
		return
	
	var data = json.data
	if not data.has("equipments"):
		print("装备JSON数据格式错误")
		return
	
	for equipment_data in data["equipments"]:
		var equipment = _create_equipment_from_data(equipment_data)
		if equipment:
			item_database[equipment.id] = equipment

func _create_equipment_from_data(data: Dictionary) -> EquipmentData:
	"""从字典数据创建装备对象"""
	if not data.has("id") or not data.has("name") or not data.has("slot"):
		return null
	
	# 转换装备槽位
	var slot_name = data["slot"].to_upper()
	# 特殊处理：映射不匹配的槽位名称
	if slot_name == "RING":
		slot_name = "RING1"  # 将"RING"映射到"RING1"
	elif slot_name == "ARMOR":
		slot_name = "CHEST"  # 将"ARMOR"映射到"CHEST"（胸甲）
	var slot = EquipmentSlot.get(slot_name)
	if slot == null:
		print("未知的装备槽位: ", slot_name, " (原始: ", data["slot"], ")")
		return null
	
	var equipment = EquipmentData.new(
		data["id"],
		data["name"],
		slot,
		data.get("description", ""),
		data.get("icon_path", "")
	)
	
	# 设置基础属性
	equipment.level_requirement = data.get("level_requirement", 1)
	equipment.value = data.get("value", 0)
	equipment.stack_size = data.get("stack_size", 1)
	
	# 设置稀有度
	var rarity_name = data.get("rarity", "COMMON").to_upper()
	equipment.rarity = ItemRarity.get(rarity_name, ItemRarity.COMMON)
	
	# 设置装备属性
	var stats = data.get("stats", {})
	equipment.strength = stats.get("strength", 0)
	equipment.agility = stats.get("agility", 0)
	equipment.intelligence = stats.get("intelligence", 0)
	equipment.stamina = stats.get("stamina", 0)
	equipment.spirit = stats.get("spirit", 0)
	equipment.critical_rate = stats.get("critical_rate", 0.0)
	equipment.cooldown_reduction = stats.get("cooldown_reduction", 0.0)
	equipment.penetration_rate = stats.get("penetration_rate", 0.0)
	equipment.critical_damage = stats.get("critical_damage", 0.0)
	equipment.physical_defense = stats.get("physical_defense", 0)
	equipment.dodge_rate = stats.get("dodge_rate", 0.0)
	equipment.block_rate = stats.get("block_rate", 0.0)
	equipment.life_steal = stats.get("life_steal", 0.0)
	equipment.toughness = stats.get("toughness", 0.0)
	equipment.movement_speed = stats.get("movement_speed", 0.0)
	equipment.status_resistance = stats.get("status_resistance", 0.0)
	equipment.status_hit_rate = stats.get("status_hit_rate", 0.0)
	equipment.elemental_damage = stats.get("elemental_damage", 0.0)
	
	return equipment

func _load_consumables_from_json():
	"""从JSON文件加载消耗品数据"""
	var file = FileAccess.open("res://data/consumables/consumables.json", FileAccess.READ)
	if file == null:
		print("无法打开消耗品数据文件")
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		print("解析消耗品JSON数据失败")
		return
	
	var data = json.data
	if not data.has("consumables"):
		print("消耗品JSON数据格式错误")
		return
	
	for consumable_data in data["consumables"]:
		var consumable = _create_consumable_from_data(consumable_data)
		if consumable:
			item_database[consumable.id] = consumable

func _create_consumable_from_data(data: Dictionary) -> ConsumableData:
	"""从字典数据创建消耗品对象"""
	if not data.has("id") or not data.has("name") or not data.has("effect_type"):
		return null
	
	var consumable = ConsumableData.new(
		data["id"],
		data["name"],
		data["effect_type"],
		data.get("effect_value", 0),
		data.get("description", ""),
		data.get("icon_path", "")
	)
	
	# 设置基础属性
	consumable.value = data.get("value", 0)
	consumable.stack_size = data.get("stack_size", 99)
	consumable.duration = data.get("duration", 0.0)
	
	# 设置稀有度
	var rarity_name = data.get("rarity", "COMMON").to_upper()
	consumable.rarity = ItemRarity.get(rarity_name, ItemRarity.COMMON)
	
	return consumable

func _load_materials_from_json():
	"""从JSON文件加载材料数据"""
	var file = FileAccess.open("res://data/materials/materials.json", FileAccess.READ)
	if file == null:
		print("无法打开材料数据文件")
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		print("解析材料JSON数据失败")
		return
	
	var data = json.data
	if not data.has("materials"):
		print("材料JSON数据格式错误")
		return
	
	for material_data in data["materials"]:
		var material = _create_material_from_data(material_data)
		if material:
			item_database[material.id] = material

func _create_material_from_data(data: Dictionary) -> MaterialData:
	"""从字典数据创建材料对象"""
	if not data.has("id") or not data.has("name") or not data.has("material_type"):
		return null
	
	var material = MaterialData.new(
		data["id"],
		data["name"],
		data["material_type"],
		data.get("description", ""),
		data.get("icon_path", "")
	)
	
	# 设置基础属性
	material.value = data.get("value", 0)
	material.stack_size = data.get("stack_size", 999)
	
	# 设置稀有度
	var rarity_name = data.get("rarity", "COMMON").to_upper()
	material.rarity = ItemRarity.get(rarity_name, ItemRarity.COMMON)
	
	return material

func get_item_data(item_id: String):
	return item_database.get(item_id)

func get_equipment_by_id(item_id: String) -> EquipmentData:
	"""根据ID获取装备数据（返回副本）"""
	var item = item_database.get(item_id)
	if item != null and item.type == ItemType.EQUIPMENT:
		var equipment = item as EquipmentData
		return equipment.duplicate_equipment()
	return null

func get_consumable_by_id(item_id: String) -> ConsumableData:
	"""根据ID获取消耗品数据"""
	var item = item_database.get(item_id)
	if item != null and item.type == ItemType.CONSUMABLE:
		return item as ConsumableData
	return null

func get_material_by_id(item_id: String) -> MaterialData:
	"""根据ID获取材料数据"""
	var item = item_database.get(item_id)
	if item != null and item.type == ItemType.MATERIAL:
		return item as MaterialData
	return null

func sell_item(item_type: ItemType, slot_index: int, quantity: int = 1) -> int:
	"""卖出物品，返回获得的金币数量"""
	var inventory = get_inventory_by_type(item_type)
	if slot_index < 0 or slot_index >= inventory.size():
		return 0
	
	var slot = inventory[slot_index]
	if slot.is_empty() or slot.quantity < quantity:
		return 0
	
	var item_data = slot.item_data
	if not item_data:
		return 0
	
	# 计算卖出价格（原价的50%）
	var sell_price = int(item_data.value * 0.5) * quantity
	
	# 移除物品
	remove_item_from_inventory(item_data.id, quantity, item_type)
	
	# 添加金币
	PlayerStatsManager.add_gold(sell_price)
	
	return sell_price

func sort_inventory(item_type: ItemType):
	"""整理背包，将物品按类型和稀有度排序"""
	var inventory = get_inventory_by_type(item_type)
	
	# 收集所有非空槽位的物品，保留完整的物品数据
	var items = []
	for i in range(inventory.size()):
		var slot = inventory[i]
		if not slot.is_empty():
			# 保存完整的物品数据，包括强化等级等属性
			var item_info = {
				"item_data": slot.item_data,  # 保存完整的物品数据对象
				"quantity": slot.quantity
			}
			items.append(item_info)
			slot.item_data = null
			slot.quantity = 0
	
	# 按稀有度和名称排序
	items.sort_custom(func(a, b):
		var item_a = a.item_data
		var item_b = b.item_data
		if item_a.rarity != item_b.rarity:
			return item_a.rarity > item_b.rarity
		return item_a.name < item_b.name
	)
	
	# 重新放置物品，使用原始的物品数据对象
	for i in range(min(items.size(), inventory.size())):
		inventory[i].item_data = items[i].item_data  # 直接使用原始物品数据
		inventory[i].quantity = items[i].quantity
	
	inventory_changed.emit()



func unequip_item(slot) -> bool:
	var equipment = equipment_slots.get(slot)
	if equipment == null:
		return false
	
	if add_item_to_inventory(equipment, 1):
		equipment_slots[slot] = null
		equipment_changed.emit(slot, null)
		return true
	return false

func get_equipped_item(slot):
	return equipment_slots.get(slot)

func add_item_to_inventory(item, quantity: int) -> bool:
	var target_inventory: Array
	
	match item.type:
		ItemType.EQUIPMENT:
			target_inventory = inventory_equipment
		ItemType.CONSUMABLE:
			target_inventory = inventory_consumable
		ItemType.MATERIAL:
			target_inventory = inventory_material
		_:
			return false
	
	var remaining = quantity
	
	for slot in target_inventory:
		if slot.can_add_item(item, remaining):
			remaining = slot.add_item(item, remaining)
			if remaining <= 0:
				break
	
	if remaining > 0:
		for slot in target_inventory:
			if slot.is_empty():
				remaining = slot.add_item(item, remaining)
				if remaining <= 0:
					break
	
	inventory_changed.emit()
	return remaining <= 0

func remove_item_from_inventory(item_id: String, quantity: int, item_type) -> int:
	var target_inventory: Array
	
	match item_type:
		ItemType.EQUIPMENT:
			target_inventory = inventory_equipment
		ItemType.CONSUMABLE:
			target_inventory = inventory_consumable
		ItemType.MATERIAL:
			target_inventory = inventory_material
		_:
			return 0
	
	var removed = 0
	var remaining = quantity
	
	for slot in target_inventory:
		if not slot.is_empty() and slot.item_data.id == item_id:
			var remove_count = min(remaining, slot.quantity)
			slot.quantity -= remove_count
			if slot.quantity <= 0:
				slot.item_data = null
				slot.quantity = 0
			removed += remove_count
			remaining -= remove_count
			if remaining <= 0:
				break
	
	inventory_changed.emit()
	return removed

func get_inventory_by_type(item_type):
	match item_type:
		ItemType.EQUIPMENT:
			return inventory_equipment
		ItemType.CONSUMABLE:
			return inventory_consumable
		ItemType.MATERIAL:
			return inventory_material
		_:
			return []

func get_total_equipment_stats() -> Dictionary:
	var total_stats = {
		"strength": 0,
		"agility": 0,
		"intelligence": 0,
		"stamina": 0,
		"spirit": 0,
		"critical_rate": 0.0,
		"cooldown_reduction": 0.0,
		"penetration_rate": 0.0,
		"critical_damage": 0.0,
		"physical_defense": 0,
		"dodge_rate": 0.0,
		"block_rate": 0.0,
		"life_steal": 0.0,
		"toughness": 0.0,
		"movement_speed": 0.0,
		"status_resistance": 0.0,
		"status_hit_rate": 0.0,
		"elemental_damage": 0.0
	}
	
	for equipment in equipment_slots.values():
		if equipment != null:
			total_stats["strength"] += equipment.get_total_strength()
			total_stats["agility"] += equipment.get_total_agility()
			total_stats["intelligence"] += equipment.get_total_intelligence()
			total_stats["stamina"] += equipment.get_total_stamina()
			total_stats["spirit"] += equipment.get_total_spirit()
			total_stats["critical_rate"] += equipment.critical_rate
			total_stats["cooldown_reduction"] += equipment.cooldown_reduction
			total_stats["penetration_rate"] += equipment.penetration_rate
			total_stats["critical_damage"] += equipment.critical_damage
			total_stats["physical_defense"] += equipment.get_total_physical_defense()
			total_stats["dodge_rate"] += equipment.dodge_rate
			total_stats["block_rate"] += equipment.block_rate
			total_stats["life_steal"] += equipment.life_steal
			total_stats["toughness"] += equipment.toughness
			total_stats["movement_speed"] += equipment.movement_speed
			total_stats["status_resistance"] += equipment.status_resistance
			total_stats["status_hit_rate"] += equipment.status_hit_rate
			total_stats["elemental_damage"] += equipment.elemental_damage
	
	return total_stats

func swap_inventory_items(type1: ItemType, index1: int, type2: ItemType, index2: int) -> bool:
	## 交换背包中两个位置的物品
	var inventory1 = get_inventory_by_type(type1)
	var inventory2 = get_inventory_by_type(type2)
	
	if index1 < 0 or index2 < 0 or index1 >= inventory1.size() or index2 >= inventory2.size():
		return false
	
	var slot1 = inventory1[index1]
	var slot2 = inventory2[index2]
	
	# 交换物品
	var temp = InventorySlot.new(slot1.item_data, slot1.quantity)
	inventory1[index1] = InventorySlot.new(slot2.item_data, slot2.quantity)
	inventory2[index2] = temp
	
	inventory_changed.emit()
	return true

func swap_equipment_items(slot1: EquipmentSlot, slot2: EquipmentSlot) -> bool:
	## 交换两个装备槽的装备
	if slot1 == slot2:
		return false
	
	var equipment1 = equipment_slots.get(slot1)
	var equipment2 = equipment_slots.get(slot2)
	
	# 验证装备类型匹配
	if equipment1 != null and not _can_equip_to_slot(equipment1, slot2):
		print("装备类型不匹配：", equipment1.name, " 不能装备到 ", _get_slot_name(slot2))
		return false
	
	if equipment2 != null and not _can_equip_to_slot(equipment2, slot1):
		print("装备类型不匹配：", equipment2.name, " 不能装备到 ", _get_slot_name(slot1))
		return false
	
	equipment_slots[slot1] = equipment2
	equipment_slots[slot2] = equipment1
	
	equipment_changed.emit(slot1, equipment2)
	equipment_changed.emit(slot2, equipment1)
	return true

func swap_equipment_with_inventory(equipment_slot: EquipmentSlot, inventory_index: int) -> bool:
	## 交换装备槽与背包中的装备
	if inventory_index < 0 or inventory_index >= INVENTORY_SIZE:
		return false
	
	var equipped_item = equipment_slots.get(equipment_slot)
	var inventory_slot = inventory_equipment[inventory_index]
	
	# 检查背包中的物品是否为装备且类型匹配
	if not inventory_slot.is_empty():
		var inventory_item = inventory_slot.item_data
		if inventory_item.type != ItemType.EQUIPMENT:
			return false
		
		var inventory_equipment_data = inventory_item as EquipmentData
		if not _can_equip_to_slot(inventory_equipment_data, equipment_slot):
			return false
		
		# 检查等级要求
		if inventory_equipment_data.level_requirement > PlayerStatsManager.get_level():
			print("等级不足，无法装备")
			return false
	
	# 执行交换
	if equipped_item != null:
		# 将装备槽中的装备放到背包
		inventory_slot.item_data = equipped_item
		inventory_slot.quantity = 1
	else:
		# 如果装备槽为空，清空背包槽位
		inventory_slot.remove_item(inventory_slot.quantity)
	
	# 将背包中的装备装备到装备槽
	if not inventory_slot.is_empty():
		var new_equipment = inventory_slot.item_data as EquipmentData
		equipment_slots[equipment_slot] = new_equipment
		inventory_slot.remove_item(1)
	else:
		equipment_slots[equipment_slot] = null
	
	equipment_changed.emit(equipment_slot, equipment_slots.get(equipment_slot))
	inventory_changed.emit()
	return true

func get_inventory_item(index: int):
	## 获取背包中指定位置的物品（优先返回非空物品）
	if index < 0 or index >= INVENTORY_SIZE:
		return null
	
	# 优先检查装备
	if not inventory_equipment[index].is_empty():
		return inventory_equipment[index].item_data
	
	# 然后检查消耗品
	if not inventory_consumable[index].is_empty():
		return inventory_consumable[index].item_data
	
	# 最后检查材料
	if not inventory_material[index].is_empty():
		return inventory_material[index].item_data
	
	return null

func use_item(index: int) -> bool:
	## 使用背包中的消耗品
	if index < 0 or index >= INVENTORY_SIZE:
		return false
	
	var slot = inventory_consumable[index]
	if slot.is_empty() or slot.item_data.type != ItemType.CONSUMABLE:
		return false
	
	var consumable = slot.item_data as ConsumableData
	print("使用了 ", consumable.name, "，效果：", consumable.effect_type, " +", consumable.effect_value)
	
	# 调用消耗品效果
	if consumable.effect_type == "heal":
		if PlayerStatsManager != null:
			PlayerStatsManager.heal(consumable.effect_value)
		else:
			print("PlayerStatsManager不可用")
	elif consumable.effect_type == "mana":
		if PlayerStatsManager != null:
			PlayerStatsManager.restore_mp(consumable.effect_value)
		else:
			print("PlayerStatsManager不可用")
	elif consumable.effect_type == "full_restore":
		if PlayerStatsManager != null:
			PlayerStatsManager.heal_full()
			PlayerStatsManager.restore_mp_full()
		else:
			print("PlayerStatsManager不可用")
	elif consumable.effect_type == "experience":
		if PlayerStatsManager != null:
			PlayerStatsManager.add_experience(consumable.effect_value)
		else:
			print("PlayerStatsManager不可用")
	elif consumable.effect_type == "cure_poison":
		# TODO: 清除中毒状态
		print("清除中毒状态")
	elif consumable.effect_type == "buff_strength":
		# TODO: 力量增益效果
		print("获得力量增益: +", consumable.effect_value, " 持续", consumable.duration, "秒")
	elif consumable.effect_type == "buff_speed":
		# TODO: 速度增益效果
		print("获得速度增益: +", consumable.effect_value, "% 持续", consumable.duration, "秒")
	else:
		print("未知的消耗品效果类型: ", consumable.effect_type)
	
	# 减少物品数量
	slot.remove_item(1)
	inventory_changed.emit()
	return true

func equip_item(index: int) -> bool:
	## 装备背包中的装备
	if index < 0 or index >= INVENTORY_SIZE:
		return false
	
	var slot = inventory_equipment[index]
	if slot.is_empty() or slot.item_data.type != ItemType.EQUIPMENT:
		return false
	
	var equipment = slot.item_data as EquipmentData
	if equipment.level_requirement > PlayerStatsManager.get_level():
		print("等级不足，无法装备")
		return false
	
	# 确定目标装备槽位
	var target_slot = equipment.slot
	
	# 戒指特殊处理：智能选择槽位
	if equipment.slot == EquipmentSlot.RING1:
		# 优先选择空的戒指槽位
		if equipment_slots.get(EquipmentSlot.RING1) == null:
			target_slot = EquipmentSlot.RING1
		elif equipment_slots.get(EquipmentSlot.RING2) == null:
			target_slot = EquipmentSlot.RING2
		else:
			# 如果两个槽位都有装备，默认替换RING1
			target_slot = EquipmentSlot.RING1
	
	# 卸下当前装备并放回原位置
	var old_equipment = equipment_slots.get(target_slot)
	if old_equipment != null:
		# 将旧装备放回到新装备的位置
		slot.item_data = old_equipment
		slot.quantity = 1
	else:
		# 如果没有旧装备，清空槽位
		slot.remove_item(1)
	
	# 装备新装备
	equipment_slots[target_slot] = equipment
	
	equipment_changed.emit(target_slot, equipment)
	inventory_changed.emit()
	return true

func _can_equip_to_slot(equipment: EquipmentData, target_slot: EquipmentSlot) -> bool:
	## 检查装备是否可以装备到指定槽位
	## 戒指类型的装备可以装备到任意戒指槽位
	if equipment.slot == target_slot:
		return true
	
	# 戒指通用性：RING1类型的装备可以装备到RING1或RING2
	if equipment.slot == EquipmentSlot.RING1 and (target_slot == EquipmentSlot.RING1 or target_slot == EquipmentSlot.RING2):
		return true
	
	return false

func clear_all_inventories():
	"""清空所有背包"""
	for i in range(INVENTORY_SIZE):
		inventory_equipment[i].item_data = null
		inventory_equipment[i].quantity = 0
		inventory_consumable[i].item_data = null
		inventory_consumable[i].quantity = 0
		inventory_material[i].item_data = null
		inventory_material[i].quantity = 0
	
	inventory_changed.emit()
	print("所有背包已清空")

func unequip_all():
	"""卸下所有装备"""
	for slot in equipment_slots.keys():
		equipment_slots[slot] = null
		# 为每个槽位发射装备变化信号
		equipment_changed.emit(slot, null)
	print("所有装备已卸下")

func add_consumable_to_inventory(consumable: ConsumableData, quantity: int) -> bool:
	"""添加消耗品到背包"""
	return add_item_to_inventory(consumable, quantity)

func add_material_to_inventory(material: MaterialData, quantity: int) -> bool:
	"""添加材料到背包"""
	return add_item_to_inventory(material, quantity)

func add_equipment_to_inventory(equipment: EquipmentData, quantity: int) -> bool:
	"""添加装备到背包"""
	return add_item_to_inventory(equipment, quantity)

func _get_slot_name(slot: EquipmentSlot) -> String:
	## 获取装备槽位名称
	match slot:
		EquipmentSlot.WEAPON:
			return "武器"
		EquipmentSlot.SHIELD:
			return "盾牌"
		EquipmentSlot.HELMET:
			return "头盔"
		EquipmentSlot.CHEST:
			return "胸甲"
		EquipmentSlot.LEGS:
			return "腿甲"
		EquipmentSlot.BOOTS:
			return "靴子"
		EquipmentSlot.GLOVES:
			return "手套"
		EquipmentSlot.RING1:
			return "戒指1"
		EquipmentSlot.RING2:
			return "戒指2"
		EquipmentSlot.NECKLACE:
			return "项链"
		EquipmentSlot.EARRING:
			return "耳环"
		_:
			return "未知装备槽"

func get_rarity_color(rarity: ItemRarity) -> Color:
	## 获取稀有度对应的颜色
	match rarity:
		ItemRarity.COMMON:
			return Color.WHITE  # 白色 - 普通
		ItemRarity.UNCOMMON:
			return Color.GREEN  # 绿色 - 不常见
		ItemRarity.RARE:
			return Color.CYAN   # 青色 - 稀有
		ItemRarity.EPIC:
			return Color.MAGENTA  # 紫色 - 史诗
		ItemRarity.LEGENDARY:
			return Color.ORANGE   # 橙色 - 传说
		_:
			return Color.WHITE

func get_rarity_name(rarity: ItemRarity) -> String:
	## 获取稀有度的中文名称
	match rarity:
		ItemRarity.COMMON:
			return "普通"
		ItemRarity.UNCOMMON:
			return "不常见"
		ItemRarity.RARE:
			return "稀有"
		ItemRarity.EPIC:
			return "史诗"
		ItemRarity.LEGENDARY:
			return "传说"
		_:
			return "未知"
